import 'package:leader_doctor_flutter/common/data/app.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../plugins/plugins_messages.g.dart';

///
/// @Author lixiaobin
/// @Date 2023/11/2
/// @Description
///
class UrlHelper {
  ///加载领医h5页面
  static String loadUrl(String url, {Map<String, String>? params}) {
    var baseH5Url = App.instance.baseH5Url ?? '';
    assert(baseH5Url != '', 'baseH5Url 为空');
    var str = baseH5Url + url;
    var index = str.indexOf('?');
    var endIndex = index == str.length - 1;
    String? s = (index == -1 || endIndex) ? '?' : null;
    params?.keys.forEach((key) {
      str += '${(endIndex ? '' : s) ?? '&'}$key=${params[key]}';
      s = null;
    });
    return str;
  }

  ///执行人参数添加
  static String? formatExecutorUrl(String url) {
    var uId = App.instance.userInfo?.id;
    var realName = App.instance.userInfo?.realName;
    if (uId == null) {
      throw Exception('参数异常 executorId:$uId executorName:$realName');
    }
    return loadUrl(url, params: {
      'executorId': uId,
      'executorName': realName ?? '',
    });
  }

  ///加载h5页面 title为空取h5页面title
  static loadH5Page(String? title, String url) async {
    if (App.hasPigeons) {
      await NativeInterface().openH5Page(title, url);
    } else {
      await launchUrl(Uri.parse(url), mode: LaunchMode.inAppWebView);
    }
  }
}
